import { getCountPageData, getStateTrend } from '../../../api/getData.js'
import { formatTime, getTimeStm } from '../../../utils/util.js';

Component({

  data: {
    moduleList: null,
    countOpt: [],
    timeOpt: [],
    timeStr: [],
    timeIndex: 0,
    curCountOpt: null,
    showLoad: false,
    username: '',
    showPicker: false,
    timeSign: '',
    nowTime: '',
    areaText: '',
    isShowAddEvent: false,
    moduleSign: '',
  },
  attached() {
    let timeStr, moduleList, countOpt, showLoad, username, moduleConfig;
    if (wx.getStorageSync('moduleList_new').length) {
        moduleList = wx.getStorageSync('moduleList_new').filter(item => item.moduleID === 'history')[0];
        countOpt = moduleList.children.filter(item=>item.moduleName==="统计图")[0].children;
        showLoad = false;
        username = wx.getStorageSync('username');
        moduleConfig = wx.getStorageSync('moduleConfig_new');
        timeStr = moduleConfig[countOpt[0].moduleID].charts.split(',');
    } else {
        moduleList = wx.getStorageSync('moduleList').filter(item => item.moduleID === 'history')[0];
        countOpt = moduleList.children[0].children;
        showLoad = false;
        username = wx.getStorageSync('username');
        let moduleConfig = wx.getStorageSync('moduleConfig');
        timeStr = moduleConfig[countOpt[0].moduleID].charts.split(',');
    }
    let stm = new Date(),
      start = formatTime(stm, 0),
      stmStart = new Date(start.split(' ')[0]),
      startTime = formatTime(stmStart, 1),
      endTime = formatTime(new Date(stmStart.getTime() + 86400000), 1);

    if (Number(timeStr[0]) >= 1440) {
      startTime = formatTime(new Date(stmStart.getTime() - 86400000 * 30), 1)
      endTime = formatTime(new Date(stmStart.getTime() + 86400000), 1);
    } else if (username === "widia") {
      showLoad = true;
      endTime = formatTime(stmStart, 1);
      startTime = formatTime(new Date(stmStart.getTime() - 86400000), 1)
    }

    this.setData({
      moduleList,
      countOpt,
      startTime,
      endTime,
      showLoad,
      curCountOpt: countOpt[0],
      setMargin: false,
    })
    this.countTimeOpt(countOpt[0].moduleID)
  },
  pageLifetimes: {
    
  },
  methods: {
    // 在用导航切换设备的时候要修改统计选项里面的值
    navCheck() {
      let moduleList, countOpt;
      if (wx.getStorageSync('moduleList_new').length) {
        moduleList = wx.getStorageSync('moduleList_new').filter(item => item.moduleID === 'history')[0];
        countOpt = moduleList.children[0].children;
      } else {
        moduleList = wx.getStorageSync('moduleList').filter(item => item.moduleID === 'history')[0];
        countOpt = moduleList.children[0].children;
      }
      if (countOpt.some(item => item.moduleName === this.data.curCountOpt.moduleName)) {
        this.setData({
          countOpt
        })
      } else {
        this.setData({
          countOpt,
          curCountOpt: countOpt[0]
        })
        let customCountOpt = this.selectComponent("#countOpt");
        customCountOpt.setTimeOpt()
      }
      this.getCountOptData()
    },
    // 显示图表下方的开始时间和结束时间和对应状态的
    showArea(val) {
      this.setData({
        areaText: val.detail
      })
    },
    // 显示添加事件的弹框
    showAddEvent() {
      this.setData({
        isShowAddEvent: true
      })
    },
    // 关闭添加事件的弹框
    closeAddEvent() {
      this.setData({
        isShowAddEvent: false
      })
      this.getCountOptData()
    },
    // 计算出时间粒度数据
    countTimeOpt(sign){
      let [moduleConfig, timeStr, timeOpt] = ['', '', []]
      if (wx.getStorageSync('moduleList_new').length) {
        moduleConfig = wx.getStorageSync('moduleConfig_new');
        timeStr = moduleConfig[sign].charts.split(',');
        timeOpt = [];
      } else {
        moduleConfig = wx.getStorageSync('moduleConfig');
        timeStr = moduleConfig[sign].charts.split(',');
        timeOpt = [];
      }

       //由于数据格式发生变更， 这里用新的变量进行转化和传输，避免影响原来的逻辑
      let newTimeStr = [];  

      timeStr.forEach(itemStr => {
       //服务端端数据格式变更 为 "1440:长期&Long time", "10:实时&Real time"
       let time=itemStr.split(':');
       let item = time[0],
           name = itemStr.indexOf('&')>0?time[1].split('&')[0]:'';

        item = item-0;

        if(name){
          timeOpt.push({
            label: name,
          })
        }else{
          let lable = '';
          if(item < 1){
            lable = '1分钟';
          } else if (item < 60) {
            lable = Math.floor(item) + '分钟';
          } else if (item / 60 < 24) {
            lable = Math.floor(item / 60) + '小时'
          } else {
            lable = Math.floor(item / 60 / 24) + '天'
          }
          timeOpt.push({
            label: lable,
          })
        }

        newTimeStr.push(item);
      })

      this.ChangeTimeRange(sign,newTimeStr[0]);

     
      this.setData({
        CurrentSign:sign,
        timeOpt,
        timeStr : newTimeStr,
        moduleSign: sign
      })
      this.getCountOptData()
    },
    // 设置时间范围
    ChangeTimeRange(sign,time){
      /**
       * sign
       * decro history_chart_health_cyle 
       * xiamenyc history_trendAssessment
       * 
      */
      switch (time) {
        case 1440:
          var stm = new Date(),
            start = formatTime(stm, 0),
            stmStart = new Date(start.split(' ')[0]),
            startTime = formatTime(new Date(stmStart.getTime() - 86400000 * 29), 1),
            endTime = formatTime(new Date(stmStart.getTime()+ 86400000), 1);

          this.setData({
            startTime,
            endTime
          })
          break;
        case 60:
          var stm = new Date(),
            start = formatTime(stm, 0),
            stmStart = new Date(start.split(' ')[0]),
            startTime = formatTime(stmStart, 1),
            endTime = formatTime(new Date(stmStart.getTime() + 86400000), 1);
          this.setData({
            startTime,
            endTime
          })
          break;
        case 10:
          var stm = new Date(),
            start = formatTime(stm, 0),
            stmStart = new Date(),
            startTime = formatTime(stmStart, 1),
            endTime = formatTime(new Date(stmStart.getTime() + 86400000), 1);
          this.setData({
            startTime,
            endTime
          })
          break;
      } 
    },

    // 统计选项子组件触发的函数
    getCountOpt(e) {
      let curCountOpt = e.detail.curOpt;
      this.setData({ 
        curCountOpt,
        timeIndex: 0
       });
      let timeOpt = this.selectComponent("#timeOpt");
      timeOpt.setTimeOpt()
      this.countTimeOpt(curCountOpt.moduleID);
    },

    // 时间粒度子组件触发的函数
    getTimeOpt(e){
      let { index } = e.detail; 

      // this.ChangeTimeRange(this.data.moduleSign,this.data.timeStr[index]);
      this.setData({
        timeIndex: index,
      })
      
      this.getCountOptData()
    },

    // 获取数据
    getCountOptData(){
      // 每次请求数据的时候把图表下面的显示的详细内容清空
      this.setData({
        areaText: ''
      })
      let { startTime, endTime, timeStr, timeIndex, curCountOpt, timeOpt } = this.data;
        startTime = startTime.split('-').join('/');
        endTime = endTime.split('-').join('/');
      
      let stmStartTime = Math.round(new Date(startTime)),
        stmEndTime = Math.round(new Date(endTime));
      
        

      let data = {
        minute: timeStr[timeIndex],
        startTime: stmStartTime ,
        endTime: stmEndTime
      }
      if (curCountOpt.moduleName === "状态趋势"){
        getStateTrend(data).then(this.then.bind(this))
        return
      }
      if (curCountOpt.moduleID === 'history_trendAssessment' || curCountOpt.moduleID === 'history_trendHealth') { // 趋势评估的size 是2
        data.size = 2;
      }
      getCountPageData(data).then(this.then.bind(this))
    },

    then(res){
      let { timeIndex, timeOpt } = this.data,
        timeValue = timeOpt[timeIndex].label,
        reg = /天/g,
        regBool = reg.test(timeValue),
        isDay = false;
        if (regBool){
          let newArr = timeValue.split('');
          newArr.pop()
          let day = newArr.join('')*1;
          day >= 1 && (isDay = true)
        }
      // console.log('判断DOM元素是否加载完毕',this.selectComponent('.history-echarts'))
      // 这里加一层判断当返回的resCode === 'Fail'
      if (res.resCode === 'SUCCESS') {
        this.selectComponent('.history-echarts').countEcharts(res, isDay)
      } else {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 选择时间picker相关
    pickerShow: function (e) {
      let sign = e.currentTarget.dataset.sign;
      this.triggerEvent("setNavMargin", { showDialog: 'show'});
      this.setData({
        showPicker: true,
        chartHide: true,
        timeSign: e.currentTarget.dataset.sign
      });
      this.selectComponent('.date-picker').formMatInit(sign == 0 && this.data.startTime || this.data.endTime)
     
    },

    handleSelecteDate (e) {
      let { date, timeSign} = e.detail,
      
        timeArr = [getTimeStm(this.data.startTime), getTimeStm(this.data.endTime)];
      
      timeArr[timeSign] = getTimeStm(date);
      console.log(this.data, timeSign)
      // console.log(this.data.timeSign)
      // 这里更改了判断的时机 只有点击选择结束时间的时候再做判断
      // if (this.data.timeSign === '1') {
        if (timeArr[0] === timeArr[1]) {
          wx.showToast({
            title: '时间不能相等',
            icon: 'none'
          })
          return
        }

        if (timeArr[0] > timeArr[1]) {
          wx.showToast({
            title: '开始时间不能大于结束时间',
            icon: 'none'
          })
          return
        }

        if (timeArr[1] - timeArr[0] > 15724800000) {
          wx.showToast({
            title: '时间不能大于半年',
            icon: 'none'
          })
          return
        }
      // }


      // if (this.data.moduleSign === 'history_chart_health_cyle') {
      //   switch (wx.getStorageSync('moduleConfig').history_chart_state_cyle.charts.split(',')[this.data.timeIndex] * 1) {
      //     case 1440:
      //       let stm = new Date(),
      //         start = formatTime(stm, 0),
      //         stmStart = new Date(start.split(' ')[0]),
      //         startTime = formatTime(stmStart, 1)
      //       if (timeArr[0] > new Date(startTime).getTime() || timeArr[1] > new Date(startTime).getTime()) {
      //         wx.showToast({
      //           title: '选择的时间不能超过今天零点',
      //           icon: 'none'
      //         })
      //         return
      //       }
      //       break;
      //     case 60:
      //       console.log(timeArr[1] > (new Date().getTime() - 3600000))
      //       if (timeArr[0] > (new Date().getTime() - 3600000) || timeArr[1] > (new Date().getTime() - 3600000)) {
      //         wx.showToast({
      //           title: '选择的时间不能超过前1小时',
      //           icon: 'none'
      //         })
      //         return
      //       }
      //       break;
      //     case 10:
      //       if (timeArr[0] > (new Date().getTime() - 600000) || timeArr[1] > (new Date().getTime() - 600000)) {
      //         wx.showToast({
      //           title: '选择的时间不能超过前10分钟',
      //           icon: 'none'
      //         })
      //         return
      //       }
      //       break;
      //   }

      // }

      let obj = {};
      obj[timeSign == 0 && "startTime" || "endTime"] = date;
      this.setData(obj)
      this.hiddencover()
      // console.log(this.data.timeSign)
      // 这里做了简单的判断 根据点击的timeSign判断选择的是开始时间或者结束时间来决定是否执行渲染图表
      // if (this.data.timeSign === '1') {
        this.getCountOptData()
      // }
    },
    hiddencover(){
      

      this.setData({
        showPicker: false,
        chartHide: false
      })
      this.triggerEvent("setNavMargin", { showDialog: '' });
    },
    pickerHide: function (e) {
      if (e.detail.time){
        let { endTime, startTime} = e.detail.time,
          stmStartTime = Math.round(new Date(startTime.split('-').join('/'))),
          stmEndTime = Math.round(new Date(endTime.split('-').join('/')));

        if ((stmStartTime === stmEndTime) || (stmEndTime - stmStartTime > 15724800000)) {
          wx.showToast({
            title: stmStartTime === stmEndTime
              && '时间不能相等'
              || '时间不能大于半年',
            icon: 'none'
          })
          return
        }
        this.setData({
          startTime,
          endTime
        });
        this.getCountOptData()
      }
      this.triggerEvent("setNavMargin", { showDialog: '' });
      this.setData({
        isPickerShow: false,
        chartHide: false
      });
    },

    bindPickerChange: function (e) {

      this.getData(this.data.sensorList[e.detail.value].id);
      this.setData({
        index: e.detail.value,
        sensorId: this.data.sensorList[e.detail.value].id
      });
    },
    setPickerTime: function (val) {
      
    }
  }
})